# Reksio - Memory Map Editor
# Copyright (C) 2023 CERN
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
#
# In applying this licence, CERN does not waive the privileges and immunities
# granted to it by virtue of its status as an Intergovernmental Organization or
# submit itself to any jurisdiction.

import reksio
import on_load_node
from expand_submap import get_submap_working_path, set_computed_filename
import sys
from pathlib import Path
import os

def on_change(main_window, index):
	attrs_model = main_window.getAttributesModel(index)
	attr = attrs_model.getAttribute(index)
	parent_container = attr.parent
	parent_node = attr.parentNode
	
	if parent_container.name == "computed":
		# no logic for computed attributes
		return
	
	if attr.name in ["address", "width", "repeat", "count", "size", "memsize", "align"]:
		on_load_node.addresser_action(main_window)
	
	if parent_node.type == "submap" and attr.name == "filename":
		
		if not main_window.hasFile():
			reksio.warn("Please save your memory map before setting submap's files, because they need to be relative to a memory map file.")
			return
		
		attrValue = Path(attr.value)

		parent_path = get_submap_working_path(parent_node, main_window)
		
		if os.path.isabs(attrValue):
			relative_path = os.path.relpath(attrValue, start=parent_path)
			attr.value = str(relative_path).replace("\\", "/") # store only forward slashes as this is the only multiplatform solution...
			set_computed_filename(parent_node, attrValue)
		else:
			# for example redo change
			absolute_path = Path(parent_path) / attrValue
			set_computed_filename(parent_node, absolute_path)

def on_change_file(main_window, index):
	pass
	#print("file changed!")
